package com.hello.sky.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hello.sky.context.BaseContext;
import com.hello.sky.model.entity.AddressBook;
import com.hello.sky.result.Result;
import com.hello.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddrController {

    @Autowired
    private AddressBookService addrService;

    @GetMapping("/list")
    public Result getAllAddr(){
        List<AddressBook> addrList = addrService.getAllAddrByCurrentUser();
        return Result.success(addrList);
    }

    @PostMapping
    public Result addAddr(@RequestBody AddressBook addressBook){
        addrService.addAddr(addressBook);
        return Result.success();
    }

    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook){
        addrService.setDefault(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable("id") Long id) {
        AddressBook addressBook = addrService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        addrService.updateById(addressBook);
        return Result.success();
    }

    @DeleteMapping("/")
    public Result deleteById(@RequestParam("id") Long id) {
        addrService.removeById(id);
        return Result.success();
    }

    @GetMapping("default")
    public Result<AddressBook> getDefault() {
        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addr = addrService.getDefaultAddr();

        if (addr != null) {
            return Result.success(addr);
        }

        return Result.error("没有查询到默认地址");
    }
}
